package kiwi.assist.dev.guieditor.command {
	import ghostcat.events.OperationEvent;
	import ghostcat.operation.load.LoadOper;
	import ghostcat.operation.load.LoadTextOper;
	import ghostcat.operation.load.QueueLoadOper;

	import kiwi.assist.dev.guieditor.event.GUIEditorEvent;
	import kiwi.assist.dev.guieditor.model.GUIEditorConfig;
	import kiwi.assist.dev.guieditor.model.StyleLibConfig;
	import kiwi.assist.dev.guieditor.view.GuiEditorView;
	import kiwi.assist.dev.util.LoadSWFOper;
	import kiwi.debug.Log;

	import org.robotlegs.mvcs.Command;

	import flash.events.Event;

	/**
	 * 编辑器的初始化加载
	 * @author zhangming.luo
	 */
	public class LoadConfigCommand extends Command {
		[Inject]
		public var config : GUIEditorConfig;
		private var configLoadOper : LoadOper;
		private var gameConfig : XMLList;
		private var configXML : XML;
		private var queue : QueueLoadOper;

		override public function execute() : void {
			super.execute();
			configLoadOper = new LoadOper("config.xml", null, onConfigLoaded, function() : void {
				Log.alert("配置文件加载错误");
			});
			configLoadOper.execute();
		}

		private function onConfigLoaded(e : Event) : void {
			configXML = new XML(configLoadOper.data);
			gameConfig = configXML..game;
			queue = new QueueLoadOper("", 1, onLibLoaded, function() : void {
				Log.alert("资源文件加载错误");
			});
			// 读取需要自动加载的库
			for each (var lib:XML in configXML..lib) {
				if (lib.@autoLoaded == "true") {
					Log.info("Load " + String(lib.@src));
					queue.commitChild(new LoadSWFOper(String(lib.@src)));
				}
			}
			queue.execute();
		}

		private function onLibLoaded(e : OperationEvent) : void {
			var view : GuiEditorView = new GuiEditorView();
			contextView.addChild(view);
			dispatch(new GUIEditorEvent(GUIEditorEvent.INIT_CONFIG, configXML));
			// 初始化游戏的配置
			var queue : QueueLoadOper = new QueueLoadOper();
			// TODO: 增加一个选择的过程
			// 加载游戏的配置
			var configLoadOper : LoadTextOper = new LoadTextOper(String(XML(gameConfig[0]).@src));
			queue.commitChild(configLoadOper);
			// 加载游戏的组件库swf
			for each (var src:XML in XML(gameConfig[0])..lib..@src) {
				queue.commitChild(new LoadSWFOper(String(src)));
			}
			queue.execute();
			queue.addEventListener(OperationEvent.OPERATION_COMPLETE, function() : void {
				dispatch(new GUIEditorEvent(GUIEditorEvent.INIT_GAMECONFIG, configLoadOper.data));
				for each (var style:StyleLibConfig in config.styles) {
					dispatch(new GUIEditorEvent(GUIEditorEvent.STYLE_SELECTION_CHANGE, style));
				}
				dispatch(new GUIEditorEvent(GUIEditorEvent.INIT_COMPLETE));
				dispatch(new GUIEditorEvent(GUIEditorEvent.NEW_PROJECT));
			});
		}
	}
}
